<template>
  <div>
    <!-- 面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域-->
    <el-card>
      <!-- 添加角色按钮-->
      <el-row>
        <el-col>
          <el-button @click="addRolesDialogVisible = true" type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表-->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop':'', 'vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限-->
              <el-col :span="19">
                <!-- 渲染二级权限-->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限，在tag里渲染-->
                  <el-col :span="18">
                    <el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning" v-for="(item3,i3) in item2.children" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button @click="showEditRolesDialog(scope.row.id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="removeRoleById(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button @click="showSetRightDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加角色的对话框-->
      <el-dialog @close="addRolesDialogClosed"
                 title="添加角色"
                 :visible.sync="addRolesDialogVisible"
                 width="50%">
        <!-- 内容主题区域-->
        <el-form :model="addRoles" :rules="addRolesRules" ref="addRolesRef" label-width="70px">
          <el-form-item label="名称" prop="roleName">
            <el-input v-model="addRoles.roleName"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="roleDesc">
            <el-input v-model="addRoles.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域-->
        <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
      </el-dialog>
      <!-- 修改角色的对话框-->
      <el-dialog
          title="修改角色"
          :visible.sync="editRolesDialogVisible"
          width="50%" @close="editRolesDialogClosed">
        <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesFormRef" label-width="70px">
          <el-form-item label="角色ID">
            <el-input v-model="editRolesForm.roleId" disabled></el-input>
          </el-form-item>
          <el-form-item label="名称" prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="roleDesc">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="editRolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRolesInfo">确 定</el-button>
  </span>
      </el-dialog>
      <!-- 分配权限的对话框-->
      <el-dialog
          title="分配权限"
          :visible.sync="setRightDialogVisible"
          width="50%" @close="setRightDialogClosed">
        <!-- 树形空间-->
        <el-tree :data="rightsList"
                 :props="treeProps"
                 show-checkbox
                 node-key="id"
                 default-expand-all
                 :default-checked-keys="defKeys"
                 ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data(){
    return {
      // 所有角色列表数据
      rolelist:[],
      addRoles:{
        roleName:'',
        roleDesc:''
      },
      // 添加对话框的显示与隐藏
      addRolesDialogVisible: false,
      // 添加验证规则
      addRolesRules: {
        roleName:[{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        },{
          min: 2,
          max: 10,
          message: '角色名称的长度在2~10个字符之间',
          trigger: 'blur'
        }],
        roleDesc:[{
          required: true,
          message: '请输入角色描述',
          trigger: 'blur'
        },{
          min: 1,
          max: 15,
          message: '密码的长度在1~15个字符之间',
          trigger: 'blur'
        }]
      },
      // 修改角色的对话框显示
      editRolesDialogVisible: false,
      // 查询到的角色信息
      editRolesForm:{},
      // 修改角色的验证规则
      editRolesFormRules:{
        roleName:[{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        },{
          min: 2,
          max: 10,
          message: '角色名称的长度在2~10个字符之间',
          trigger: 'blur'
        }],
        roleDesc:[{
          required: false,
          message: '请输入角色描述',
          trigger: 'blur'
        },{
          min: 0,
          max: 25,
          message: '角色描述的长度在0~25个字符之间',
          trigger: 'blur'
        }]
      },
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList:[],
      // 树形控件的属性绑定对象
      treeProps:{
        label: 'authName',
        // 数据源中使用children属性进行嵌套的
        children:'children'
      },
      // 默认选中的节点id值数组
      defKeys:[],
      // 当前即将分配权限的角色id
      roleId:''
    }
  },
  created() {
    this.getRolesList()
  },
  methods:{
    // 获取所有的角色列表
    async getRolesList(){
      const {data:res} = await this.$http.get('roles')
      if (res.meta.status !== 200){
        return this.$message.error('获取角色列表失败！')
      }
      this.rolelist = res.data
    },
    // 对话框关闭清空
    addRolesDialogClosed(){
      this.$refs.addRolesRef.resetFields()
    },
    // 添加角色
    addRole(){
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return
        const {data:res} = await this.$http.post('roles',this.addRoles)
        if (res.meta.status !== 201){
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        this.addRolesDialogVisible = false
        this.getRolesList()
      })
    },
    // 编辑角色
    async showEditRolesDialog(id){
      const {data:res} = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200){
        return this.$message.error('查询角色信息失败！')
      }
      this.editRolesForm = res.data
      this.editRolesDialogVisible = true
    },
    // 监听修改角色对话框的关闭
    editRolesDialogClosed(){
      this.$refs.editRolesFormRef.resetFields()
    },
    // 修改角色信息并提交
    editRolesInfo(){
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) return
        const {data:res} = await this.$http.put('roles/' + this.editRolesForm.roleId,{
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色信息失败！')
        }
        // 成功之后, 1: 关闭对话框
        this.editRolesDialogVisible = false
        // 2. 刷新数据列表
        this.getRolesList()
        // 3. 提示修改信息成功
        this.$message.success('更新角色信息成功！')
      })
    },
    // 删除用户
    async removeRoleById(id){
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        // 捕获所有报错，并直接return，下行箭头函数省略了return
      }).catch(err => err)
      // 这时，如果用户确认删除，返回的字符串为confirm
      // 如果用户取消删除，返回的字符串为cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 调用接口，真正发起请求
      const {data:res} = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRolesList()
    },
    // 根据id删除对应的三级小权限
    async removeRightById(role, rightId){
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(confirmResult !== 'confirm'){
        return this.$message.info('取消删除')
      }
      const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200){
        return this.$message.error('删除权限失败！')
      }
      // 直接调用会发生页面整体渲染，不建议
      // this.getRolesList()
      role.children = res.data
    },
    // 显示分配权限的对话框
    async showSetRightDialog(role){
      // 拿到权限id
      this.roleId = role.id
      // 获取所有的权限数据
      const {data:res} = await this.$http.get('rights/tree')
      if (res.meta.status !== 200){
        return this.$message.error('获取权限数据失败')
      }
      this.rightsList = res.data
      // 递归获取三级节点的id
      this.getLeafKeys(role,this.defKeys)

      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys数组中
    getLeafKeys(node, arr){
      // 如果node节点不包含children属性，则是三级节点
      if (!node.children){
        return arr.push(node.id)
      }
      // 如果不是三级节点，递归找出三级节点
      node.children.forEach(item => this.getLeafKeys(item,arr))

    },
    // 分配权限对话框的关闭事件
    setRightDialogClosed(){
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights(){
      const keys = [
          // ...为展开运算符
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 然后转换为以逗号分隔的字符串
      const idStr = keys.join(',')
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
      if (res.meta.status !== 200){
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }

  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}

.bdtop{
  border-top: 1px solid #eee;
}

.bdbottom{
  border-bottom: 1px solid #eee;
}

.vcenter{
  display: flex;
  align-items: center;
}
</style>